package com.service;

import cn.hutool.core.util.RandomUtil;
import com.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class MailServiceImpl implements IMailService {

    @Autowired
    //springboot 封装好的邮箱
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     * @param to
     */

    @Override
    public void sendMail(String to){
        String code= RandomUtil.randomString(4);  //产生验证码，并保存到redis
//        redisTemplate.boundValueOps(to).set(code,30,TimeUnit.MINUTES);
        redisTemplate.boundValueOps(to).set(code);
        redisTemplate.boundValueOps(to).expire(30, TimeUnit.MINUTES);

        //发送邮箱
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from);  // 发送

        message.setTo(to);  // 接收者
        message.setSubject("验证码注册");  // 标题，主题
        message.setText("你的验证码是："+code);  // 内容
        javaMailSender.send(message);
    }


    @Override
    public boolean checkCode(String mail, String code){
        //从reids取出验证码
        String redisCode=(String)redisTemplate.boundValueOps(mail).get();
        //判断验证是否正确
        boolean f=(code!=null && code.equalsIgnoreCase(redisCode));

        if (f){
            //成功要删除原来
//            redisTemplate.delete(mail);
            redisTemplate.boundValueOps(mail).expire(0,TimeUnit.MILLISECONDS);
        }

        return f;
    }

}
